package com.lhn.netty.nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 * 聊天客户端
 *
 * @author lhn
 * @date 2025/05/29 10:03
 * @since 1.0.0
 **/
public class GroupChatClient {

    // 定义属性
    private final String HOST = "127.0.0.1"; // 服务器 ip
    private final int PORT = 6667; // 服务器端口

    private Selector selector; // 选择器
    private SocketChannel socketChannel; // 通道
    private String userName; // 客户端

    // 构造器
    public GroupChatClient() throws IOException {
        // 创建  selector
        selector = Selector.open();
        // 创建 socketChannel 并 连接服务器
        socketChannel = SocketChannel.open(new InetSocketAddress(HOST, PORT));
        // 设置为  非阻塞
        socketChannel.configureBlocking(false);
        // 将  socketChannel 注册到  selector
        socketChannel.register(selector, SelectionKey.OP_READ);
        // 得到  userName
        userName = socketChannel.getLocalAddress().toString().substring(1);
        System.out.println(userName + " is ok...");
    }

    // 向服务器发送消息
    public void sendInfo(String info) {
        info = userName + " 说：" + info;
        try {
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 读取服务器消息
    public void readInfo() {
        try {
            int readChannels = selector.select(2000);
            // 有可用的通道
            if (readChannels > 0) {
                Iterator <SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    // 获取到可用通道
                    if (selectionKey.isReadable()) {
                        SocketChannel sc = (SocketChannel) selectionKey.channel();
                        // 创建  buffer
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        // 读取数据
                        sc.read(buffer);
                        String msg = new String(buffer.array());
                        System.out.println(msg.trim());
                    }
                }
            } else {
                System.out.println("没有可用的通道");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        // 启动客户端
        GroupChatClient chatClient = new GroupChatClient();
        // 启动一个线程 每隔3 秒，读取服务器消息
        new Thread() {
            @Override
            public void run() {
                while (true) {
                    System.out.println("客户端读取线程...");
                    chatClient.readInfo();
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

        Scanner  scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String s = scanner.nextLine();
            chatClient.sendInfo(s);
        }

    }

}